<template>
  <div>
    <!-- 设备维修申请表单 -->
    <el-card class="mb-20">
      <template #header>
        <div class="card-header">
          <span>设备维修申请</span>
        </div>
      </template>
      <el-form
          ref="maintenanceFormRef"
          :model="maintenanceForm"
          :rules="rules"
          label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="设备" prop="deviceId">
              <el-select
                  v-model="maintenanceForm.deviceId"
                  placeholder="请选择设备"
                  filterable
                  remote
                  :remote-method="searchDevices"
                  :loading="deviceLoading"
                  clearable
              >
                <el-option
                    v-for="device in deviceOptions"
                    :key="device.deviceId"
                    :label="device.deviceName"
                    :value="device.deviceId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修类型" prop="maintenanceType">
              <el-select v-model="maintenanceForm.maintenanceType" placeholder="请选择维修类型">
                <el-option label="例行维护" value="routine" />
                <el-option label="故障维修" value="repair" />
                <el-option label="升级维护" value="upgrade" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计维修日期" prop="maintenanceDate">
              <el-date-picker
                  v-model="maintenanceForm.maintenanceDate"
                  type="date"
                  placeholder="选择预计维修日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="维修描述" prop="description">
              <el-input
                  v-model="maintenanceForm.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入维修描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="维修服务商" prop="maintenanceBy">
              <el-input
                  v-model="maintenanceForm.maintenanceBy"
                  placeholder="请输入维修服务商"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="submitMaintenanceApplication">提交维修申请</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 设备维修记录列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备维修记录</span>
        </div>
      </template>
      <el-table :data="maintenanceRecords" style="width: 100%" border>
        <el-table-column prop="maintenanceId" label="维修单号" />
        <el-table-column prop="deviceName" label="设备名称" />
        <el-table-column prop="maintenanceType" label="维修类型">
          <template #default="scope">
            {{ formatMaintenanceType(scope.row.maintenanceType) }}
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceDate" label="维修日期" />
        <el-table-column prop="description" label="维修描述" />
        <el-table-column prop="cost" label="维修费用" />
        <el-table-column prop="maintenanceBy" label="维修服务商" />
        <el-table-column label="状态" width="120">
          <template #default="scope">
            {{ formatStatus(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" link @click="viewDetails(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          class="mt-20"
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="handlePageChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {
  submitMaintenanceApplicationApi,
  getMaintenanceRecordsApi
} from '@/api/maintenance.js';
import { queryDevices } from '@/api/device.js';

// 维修申请表单数据
const maintenanceForm = reactive({
  deviceId: '',
  maintenanceType: '',
  maintenanceDate: '',
  description: '',
  maintenanceBy: ''
});

// 表单验证规则
const rules = {
  deviceId: [{required: true, message: '请选择设备', trigger: 'change'}],
  maintenanceType: [{required: true, message: '请选择维修类型', trigger: 'change'}],
  maintenanceDate: [{required: true, message: '请选择预计维修日期', trigger: 'change'}],
  description: [{required: true, message: '请输入维修描述', trigger: 'blur'}],
  maintenanceBy: [{required: true, message: '请输入维修服务商', trigger: 'blur'}]
};

// 获取表单引用
const maintenanceFormRef = ref(null);

// 设备选择相关
const deviceOptions = ref([]);
const deviceLoading = ref(false);

// 搜索图像搜索功能
const searchDevices = async (query) => {
  deviceLoading.value = true;
  try {
    let params = {};
    if (query) {
      params = { search: query };
    }
    const response = await queryDevices(params);
    deviceOptions.value = response.data;
  } catch (error) {
    console.error(error);
  } finally {
    deviceLoading.value = false;
  }
};

// 提交维修申请
const submitMaintenanceApplication = () => {
  maintenanceFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await submitMaintenanceApplicationApi(maintenanceForm);
        ElMessage.success('维修申请提交成功');
        // 清空表单
        resetForm();
        // 刷新维修记录列表
        getMaintenanceRecords();
      } catch (error) {
        ElMessage.error('维修申请提交失败');
        console.error(error);
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  maintenanceFormRef.value.resetFields();
};

// 维修记录列表相关逻辑
const maintenanceRecords = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 获取维修记录列表
const getMaintenanceRecords = async () => {
  try {
    const response = await getMaintenanceRecordsApi({
      page: currentPage.value,
      pageSize: pageSize.value,
    });
    maintenanceRecords.value = response.data.list;
    total.value = response.data.total;
  } catch (error) {
    console.error(error);
  }
};

// 格式化维修类型
const formatMaintenanceType = (type) => {
  const typeMap = {
    routine: '例行维护',
    repair: '故障维修',
    upgrade: '升级维护',
  };
  return typeMap[type] || type;
};

// 格式化状态
const formatStatus = (row) => {
  // 这里可以根据业务逻辑动态计算状态
  // 例如，根据当前日期和 next_maintenance_date 判断状态
  const today = new Date().toISOString().split('T')[0];
  if (row.next_maintenance_date && row.next_maintenance_date > today) {
    return '待维修';
  } else if (row.maintenanceDate && row.maintenanceDate <= today) {
    return '已完成';
  } else {
    return '进行中';
  }
};

// 查看维修详情
const viewDetails = (row) => {
  console.log('查看维修详情:', row);
  // 这里可以实现跳转到详情页或弹出详情对话框
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  getMaintenanceRecords();
};

// 页面加载时获取维修记录和设备列表
onMounted(() => {
  getMaintenanceRecords();
  searchDevices('');
});
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  font-size: 18px;
}

.mt-20 {
  margin-top: 20px;
}
</style>
